﻿using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;

namespace xxpl1.Connection
{
    public class Connection : IDisposable
    {
        private readonly ConnectioPool connectioPool;
        private readonly string server;
        private Socket s4;
        private SslStream stream;

        public Connection(ConnectioPool connectioPool, string server)
        {
            this.connectioPool = connectioPool;
            this.server = server;
        }

        public void PrepareConnection()
        {
            if (s4 != null && s4.Connected)
                return;

            if (s4 != null)
            {
                stream.Dispose();
                s4.Shutdown(SocketShutdown.Both);
                s4.Close();
                s4.Dispose();
            }

            s4 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            s4.Connect(server, 443);

            stream = new SslStream(new NetworkStream(s4, true));

            stream.AuthenticateAsClient("java2theworld.appspot.com", null, SslProtocols.Default, false);
        }

        public void ReleaseConnection()
        {
            connectioPool.ReleaseConnection(this);
        }

        public void Dispose()
        {
            stream.Dispose();
            s4.Dispose();
        }

        public void Write(byte[] bytes)
        {
            stream.Write(bytes, 0, bytes.Length);
        }

        public int Read(byte[] buffer, int offset, int length)
        {
            return stream.Read(buffer, offset, length);
        }
    }
}
